package com.onlinevideo.servlet;

import cn.hutool.json.JSONUtil;
import com.onlinevideo.dao.AuthorityDao;
import com.onlinevideo.data.ResultBean;
import com.onlinevideo.entity.Authority;
import com.onlinevideo.service.AuthorityService;
import com.onlinevideo.service.impl.AuthorityServiceImpl;
import com.onlinevideo.util.MyBeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class AuthorityServlet extends BaseServlet {

    private PrintWriter writer = null ;

    private AuthorityService  authorityService= new AuthorityServiceImpl();

    protected void queryByRoleId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
         writer = resp.getWriter();
        String roleId = req.getParameter("roleId");
        List<Authority> authorities = authorityService.queryByRoleId(Long.valueOf(roleId));
        System.out.println(roleId);
        System.out.println(authorities);
        if(authorities == null||authorities.size()<=0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("该角色暂无任何权限",authorities)));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("",authorities)));
        }
    }

    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writer = resp.getWriter();
        Authority authority = MyBeanUtils.set(Authority.class, req.getParameterMap());
        int result = authorityService.insert(authority);
        if(result<=0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError(authority.getUrl()+"添加失败")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess(authority.getUrl()+"添加成功")));
        }
    }


    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writer = resp.getWriter();
        String authorityId = req.getParameter("id");
        int result = authorityService.delete(Long.valueOf(authorityId));
        if(result<=0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("编号:"+authorityId+"删除失败")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("编号:"+authorityId+"删除成功")));
        }
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writer = resp.getWriter();
        Authority authority = MyBeanUtils.set(Authority.class, req.getParameterMap());
        int result = authorityService.update(authority);
        if(result<=0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError(authority.getUrl()+"修改失败")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess(authority.getUrl()+"修改成功")));
        }
    }
}
